package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.entity.ShoppingCart;
import com.itheima.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * ClassName: ShoppingCartController
 * Package: com.itheima.controller
 * Description:
 *
 * @Author: @Albert
 * @Version: 1.0
 */
@RestController
@Slf4j
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService cartService;

    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart cart){
        log.info("购物车数据{}",cart.toString());
        //设置用户ID,指定当前哪个用户带的购物车
        Long currentId = BaseContext.getCurrentId();
        cart.setUserId(currentId);
        //查询当前菜品或者套餐是否在购物车中
        Long dishId = cart.getDishId();
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,currentId);
        if(dishId!=null){
            //添加为菜品
            wrapper.eq(ShoppingCart::getDishId,dishId);
        }else{
            wrapper.eq(ShoppingCart::getDishId,dishId);
        }
        ShoppingCart one = cartService.getOne(wrapper);

        //如果存在就在原来基础上加一
        if(one!=null){
            Integer number = one.getNumber();
            one.setNumber(number+1);
            cartService.updateById(one);
        }else{
            //不存在添加购物车数量唯一
            cart.setNumber(1);
            cartService.save(cart);
            one = cart;
        }
        return R.success(one);
    }

    //查看购物车
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(){
        log.info("查看购物车");
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        wrapper.orderByAsc(ShoppingCart::getCreateTime);
        List<ShoppingCart> list = cartService.list(wrapper);
        return  R.success(list);
    }
    //清理购物车
    @DeleteMapping("/clean")
    public R<String> clean(){
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper();
        wrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        cartService.remove(wrapper);
        return R.success("清理购物车成功");
    }
}
